<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { RouterLink } from 'vue-router'
import { useUserStore } from '../stores/user'
import { familyApi, recipeApi } from '../request'
import type { Recipe } from '../request/api/recipe'

const userStore = useUserStore()
const dailyRecommendations = ref<{
  breakfast: Recipe[]
  lunch: Recipe[]
  dinner: Recipe[]
}>({
  breakfast: [],
  lunch: [],
  dinner: []
})
const isLoading = ref(false)
const error = ref('')

// 获取每日推荐
const fetchDailyRecommendations = async () => {
  try {
    isLoading.value = true
    error.value = ''

    // 先获取家庭信息
    let familyInfo = null
    if (userStore.user?.familyId) {
      familyInfo = await familyApi.getFamily(userStore.user.familyId)
    }
    
    // 根据家庭信息设置请求参数
    const params = {
      spicy: familyInfo?.preferences?.spicyLevel > 0 ?? true,
      spicyLevel: familyInfo?.preferences?.spicyLevel ?? 5,
      allergies: familyInfo?.preferences?.allergies?.join(',') ?? '',
      familyId: userStore.user?.familyId
    }

    const response = await recipeApi.getDailyRecommendation(params)
    dailyRecommendations.value = response
  } catch (e) {
    console.error('获取每日推荐失败:', e)
    error.value = '获取推荐失败，请稍后重试'
  } finally {
    isLoading.value = false
  }
}

// 获取菜品类型的样式
const getTypeStyle = (type: string) => {
  const styleMap: Record<string, string> = {
    meat: 'bg-red-100 text-red-600',
    vegetable: 'bg-green-100 text-green-600',
    soup: 'bg-blue-100 text-blue-600',
    other: 'bg-gray-100 text-gray-600'
  }
  return styleMap[type] || styleMap.other
}

// 获取菜品类型的中文名称
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    meat: '荤菜',
    vegetable: '素菜',
    soup: '汤类',
    other: '其他'
  }
  return typeMap[type] || '其他'
}

onMounted(fetchDailyRecommendations)
</script>

<template>
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="flex justify-between items-center mb-8">
      <h1 class="text-3xl font-bold text-gray-900">今日推荐</h1>
      <RouterLink
        to="/create-recipe"
        class="btn btn-primary"
      >
        创建新菜谱
      </RouterLink>
    </div>

    <div v-if="isLoading" class="text-center py-12">
      <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto"></div>
      <p class="mt-4 text-gray-600">加载推荐中...</p>
    </div>

    <div v-else-if="error" class="text-center py-12">
      <p class="text-red-500">{{ error }}</p>
      <button
        @click="fetchDailyRecommendations"
        class="mt-4 btn btn-primary"
      >
        重试
      </button>
    </div>

    <div v-else>
      <!-- 早餐推荐 -->
      <div class="mb-12">
        <h2 class="text-2xl font-bold text-gray-900 mb-6">早餐推荐</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div
            v-for="recipe in dailyRecommendations.breakfast"
            :key="recipe.id"
            class="card hover:shadow-lg transition-shadow duration-200"
          >
            <RouterLink :to="`/recipe/${recipe.id}`">
              <img
                :src="recipe.imageUrl"
                :alt="recipe.name"
                class="w-full h-48 object-cover"
              />
              <div class="p-4">
                <h3 class="text-xl font-semibold text-gray-900">{{ recipe.name }}</h3>
                <div class="mt-2 flex items-center space-x-2">
                  <span
                    class="inline-block px-2 py-1 text-xs font-medium rounded-full"
                    :class="getTypeStyle(recipe.type)"
                  >
                    {{ getTypeText(recipe.type) }}
                  </span>
                  <span class="text-sm text-gray-500">
                    {{ recipe.cookingTime }}分钟
                  </span>
                </div>
              </div>
            </RouterLink>
          </div>
        </div>
      </div>

      <!-- 午餐推荐 -->
      <div class="mb-12">
        <h2 class="text-2xl font-bold text-gray-900 mb-6">午餐推荐</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div
            v-for="recipe in dailyRecommendations.lunch"
            :key="recipe.id"
            class="card hover:shadow-lg transition-shadow duration-200"
          >
            <RouterLink :to="`/recipe/${recipe.id}`">
              <img
                :src="recipe.imageUrl"
                :alt="recipe.name"
                class="w-full h-48 object-cover"
              />
              <div class="p-4">
                <h3 class="text-xl font-semibold text-gray-900">{{ recipe.name }}</h3>
                <div class="mt-2 flex items-center space-x-2">
                  <span
                    class="inline-block px-2 py-1 text-xs font-medium rounded-full"
                    :class="getTypeStyle(recipe.type)"
                  >
                    {{ getTypeText(recipe.type) }}
                  </span>
                  <span class="text-sm text-gray-500">
                    {{ recipe.cookingTime }}分钟
                  </span>
                </div>
              </div>
            </RouterLink>
          </div>
        </div>
      </div>

      <!-- 晚餐推荐 -->
      <div>
        <h2 class="text-2xl font-bold text-gray-900 mb-6">晚餐推荐</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div
            v-for="recipe in dailyRecommendations.dinner"
            :key="recipe.id"
            class="card hover:shadow-lg transition-shadow duration-200"
          >
            <RouterLink :to="`/recipe/${recipe.id}`">
              <img
                :src="recipe.imageUrl"
                :alt="recipe.name"
                class="w-full h-48 object-cover"
              />
              <div class="p-4">
                <h3 class="text-xl font-semibold text-gray-900">{{ recipe.name }}</h3>
                <div class="mt-2 flex items-center space-x-2">
                  <span
                    class="inline-block px-2 py-1 text-xs font-medium rounded-full"
                    :class="getTypeStyle(recipe.type)"
                  >
                    {{ getTypeText(recipe.type) }}
                  </span>
                  <span class="text-sm text-gray-500">
                    {{ recipe.cookingTime }}分钟
                  </span>
                </div>
              </div>
            </RouterLink>
          </div>
        </div>
      </div>

      <!-- 无推荐时的提示 -->
      <div
        v-if="
          dailyRecommendations.breakfast.length === 0 &&
          dailyRecommendations.lunch.length === 0 &&
          dailyRecommendations.dinner.length === 0
        "
        class="text-center py-12"
      >
        <p class="text-gray-500">暂无推荐菜谱</p>
        <RouterLink
          to="/create-recipe"
          class="mt-4 btn btn-primary inline-block"
        >
          创建第一个菜谱
        </RouterLink>
      </div>
    </div>
  </div>
</template>